package com.zzzzzz.oms.driver;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.Validator;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.plugins.shiro.I;
import com.zzzzzz.utils.DateTimeUtils;

@Service
public class DriverService {
	@Resource
	public DriverDao driverDao;
	
	@Resource
	public Validator validator;
	
	// 增加、修改
	@Transactional
	public int save(Driver driver, I i) {
		driver.setUpdDt(new Date());
		driver.setUpdBy(i.getId());
		if (driver.getId() == null) {
			driver.setAddDt(new Date());
			driver.setAddBy(i.getId());
			driver.setPlatformId(i.getPlatformId());
			driverDao.add(driver);
		} else {
			driverDao.updById(driver);
		}
		return 1;
	}
	
	// 导入
	@Transactional
	public List<BaseData> batchAdd(List<Driver> list, I i) {
		logger.info("driver batchAdd validate start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		//start validate
		int errTt = 0;// 错误信息条数
		int susTt = 0;// 正确信息条数
		BaseData baseData;
		//用于存放信息
		List<BaseData> listMsg = new ArrayList<BaseData>();
		for (Driver driver : list) {
			//验证是否为空值
			if(StringUtils.isBlank(driver.getCd())){
				baseData = new BaseData();
				baseData.setErrMsg("代码"+driver.getCd()+"为无效值");
				listMsg.add(baseData);
				errTt++;
			}else{									
					//如果没存在就导入
					driver.setSt(0);
					driver.setPlatformId(i.getPlatformId());
					if(StringUtils.isBlank(driver.getPhone())){
						driver.setPhone(null);
					}
					try{
						save(driver, i);
						susTt++;
					}catch(DuplicateKeyException e){
						baseData = new BaseData("-1", String.format("代码" + driver.getCd() + "已经存在"));
						listMsg.add(baseData);
						errTt++;
					}
					
				}
		}
		baseData = new BaseData();
		baseData.setErrMsg("总共有" + (susTt + errTt) + "行记录；共有" + susTt+ "行记录导入成功；共有" + errTt + "行记录导入失败；");
		listMsg.add(baseData);
		logger.info("driver batchAdd save end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		return listMsg;
	}

	private static final Logger logger = LoggerFactory.getLogger(Driver.class);
}
